from building import *
import os
import zipfile

src = []
inc = []

# check if .h or .hpp files exsit
def check_h_hpp_exsit(path):
    file_dirs = os.listdir(path)
    for file_dir in file_dirs:
        if os.path.splitext(file_dir)[1] in ['.h', '.hpp']:
            return True
    return False

user_libraries_root_path = GetCurrentDir()

# Find and deal the ZIP file first
files = os.listdir(user_libraries_root_path)
for file in files:
    if os.path.isfile(file) == True:
        splitext = os.path.splitext(file)
        if splitext[1] == '.zip':
            # unzip the file
            zFile = zipfile.ZipFile(os.path.join(user_libraries_root_path, file), 'r')
            for fileM in zFile.namelist():
                zFile.extract(fileM, '.')
            zFile.close()
            os.remove(file) # delete the zip file

# Add all C/C++ and header files into the group
for root, dirs, files in os.walk(GetCurrentDir()):
    for dir in dirs:
        current_path = os.path.join(root,dir)

        # exclude 'examples' folder
        if 'examples' in current_path: 
            continue

        # add all .c and .cpp file
        src = src + Glob(os.path.join(current_path, '*.c'))
        src = src + Glob(os.path.join(current_path, '*.cpp'))

        # add .h and .hpp path
        if check_h_hpp_exsit(current_path):
            inc = inc + [current_path]

group = DefineGroup('Arduino-library', src, depend = ['PKG_USING_RTDUINO'], CPPPATH = inc)

Return('group')
